﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Threading.Tasks;
using RichTextEditor;
using System.Threading;
using System.Diagnostics;

namespace EditorLauncher
{
    public class Service : IService
    {
        private static Thread thread;
        private static ComLoader editorLoader;
        private static bool loaded;
        private ICallback callbackChannel;
        public static bool IsShutdown { get; set; }

        public string Connect()
        {
            callbackChannel = OperationContext.Current.GetCallbackChannel<ICallback>();

            return "Connected";
        }

        public string LoadEditor()
        {
            return LoadEditorWithData(null, null);
        }

        public string Close()
        {
            editorLoader.CloseEditor();

            IsShutdown = true;

            return "Closing";
        }

        public string LoadEditorWithData(byte[] imageData, string richText)
        {
            if (loaded)
            {
                editorLoader.CloseEditor();
            }
            else if (editorLoader == null)
            {
                editorLoader = new ComLoader();

                editorLoader.OnRichText += (t) =>
                {
                    callbackChannel.OnRichText(t);
                };

                editorLoader.OnImage += (ref byte[] i) =>
                {
                    callbackChannel.OnImage(i);
                };

                editorLoader.OnClose += () =>
                {
                    loaded = false;
                    callbackChannel.OnClose();
                };
            }

            thread = new Thread(() =>
            {
                loaded = true;

                editorLoader.ImageData = imageData;
                editorLoader.RichText = richText;
                
                editorLoader.LoadEditor();
                loaded = false;
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            return "Loading";
        }
    }
}
